#
from typing import Any
import os
from fastapi import FastAPI, File, Form, UploadFile, HTTPException
from fastapi.responses import HTMLResponse, FileResponse, StreamingResponse
from fastapi.responses import HTMLResponse, Response, StreamingResponse
import uvicorn  # 新增导入
from config.app_config import AppConfig as AC

g_obj_db = {}

app = FastAPI()

file_seq = 0
static_folder = 'work/files'

@app.post("/uploadFile")
async def upload_file(
    fn_ext: str = Form(..., title="用户ID"),
    val: UploadFile = File(..., title="图片文件", description="上传的图片文件")
):
    '''
    上传文件
    '''
    global file_seq
    # 读取二进制内容
    content = await val.read()
    file_seq += 1
    upload_fn = f'{static_folder}/fn_{file_seq:08d}.{fn_ext}'
    with open(upload_fn, 'wb') as wfd:
        wfd.write(content)
    return {'status': 'OK', 'size': len(content), 'url': f'fn_{file_seq:08d}.{fn_ext}'}

@app.post("/uploadObj")
async def upload_obj(
    key: str = Form(..., title="用户ID"),
    val: UploadFile = File(..., title="图片文件", description="上传的图片文件")
):
    '''
    上传文件
    '''
    # 读取二进制内容
    content = await val.read()
    print(f"Received {len(content)} bytes from {val.filename};")
    print(f'@@@@@ store {key}: {len(content)};')
    g_obj_db[key] = content
    return {'status': 'OK', 'size': len(content)}

# 文件下载功能 - 返回文件响应
@app.get("/download/{filename}")
async def download_file(filename: str):
    file_path = os.path.join(static_folder, filename)
    if not os.path.exists(file_path):
        raise HTTPException(status_code=404, detail="文件不存在")
    return FileResponse(file_path, filename=filename)

# @app.post("/upload")
# async def upload_obj(
#     key: str = Form(..., title="用户ID"),
#     val: UploadFile = File(..., title="图片文件", description="上传的图片文件")
# ):
#     '''
#     上传二进制对象，其值将保存到g_obj_db中，不保存为文件
#     '''
#     # 读取二进制内容
#     content = await val.read()
#     print(f"Received {len(content)} bytes from {val.filename};")
#     print(f'@@@@@ store {key}: {len(content)};')
#     g_obj_db[key] = content
#     return {'status': 'OK', 'size': len(content)}

@app.get('/getKStr')
async def get_kstr(key:str) -> Any:
    if key in g_obj_db:
        return {'status': 'OK', 'val': g_obj_db[key]}
    else:
        return {'status': 'OK', 'val': None}

@app.get('/getKeyObj')
async def get_key_obj(key:str) -> Any:
    # 直接返回二进制响应
    return Response(
        content=g_obj_db[key],
        media_type="application/octet-stream",
        headers={"Content-Disposition": f"attachment; filename=random_{len(g_obj_db[key])}_bytes.bin"}
    )


# 可选：添加其他路由
@app.get('/')
def read_root():
    return {"message": "FastMCP 服务正在运行"}

class McpDb(object):
    def __init__(self):
        self.name = 'apps.cpm.mcp.mcp_db.McpDb'

    @staticmethod
    def startup() -> None:
        uvicorn.run('apps.cpm.mcp.mcp_db:app', host="0.0.0.0", port=8090, reload=True)

if '__main__' == __name__:
    McpDb.startup()